package com.aruba.thymeleaf.controller;

import com.aruba.thymeleaf.bean.Emp;
import com.aruba.thymeleaf.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmpController {
    @Autowired
    private EmpService empService;

    @RequestMapping("findAllEmp")
    @ResponseBody
    public List<Emp> findAllEmp() {
        return empService.findAllEmp();
    }

    @RequestMapping("findEmpByPage/{pageSize}/{pageNum}")
    @ResponseBody
    public List<Emp> findEmpByPage(@PathVariable("pageSize") Integer pageSize,
                                   @PathVariable("pageNum") Integer pageNum) {
        return empService.findEmpByPage(pageSize, pageNum);
    }


    @RequestMapping("showEmpList")
    public ModelAndView showEmpList(ModelAndView modelAndView, HttpServletRequest req, HttpSession session) {
        List<Emp> allEmpList = empService.findAllEmp();
        modelAndView.setViewName("showEmpList");
        Map<String, Object> model = modelAndView.getModel();
        model.put("empList", allEmpList);

        // 向request域放数据
        req.setAttribute("msg", "requestMessage");
        // 向session域放数据
        session.setAttribute("msg", "sessionMessage");
        // 向application域放数据
        req.getServletContext().setAttribute("msg", "applicationMessage");

        return modelAndView;
    }

    @RequestMapping("deleteEmpByNoAndName")
    public String deleteEmpByNoAndName(Integer empno, String ename) {
        boolean success = empService.deleteEmpByNoAndName(empno, ename);
        return "redirect:showEmpList";
    }

}
